// JavaScript Document

var OurGame = {
    FPSlimit:30,
    curFPS:0,
    numFramesDrawn:0,
    totalFramesDrawn:0,
    fpsInterval:setInterval(updateFPS, 1000),
    numResourcesLoaded:0,
    totalResources:4,
    gameModeSelected:false,
    gameModes:null,
    canvas:null,
    ctx:null,
    images:{},
    grid:32,
    maxGrid:48,
    backGrid:128,
    maxBackGrid:192,
    offSet:8,
    backOffset:32,
    mapLoaded:false,
    contentLoaded:false,
    players:[],
    bombs:[],
    buttons:null,
    lvl:1,
    keys:[],
    mapFiles:[],
    keyLock:[],
    booleanMap:[],
    isGameOver:false
};


window.addEventListener('keydown', keyDown, true);
window.addEventListener('keyup', keyUp, true);
window.addEventListener('blur', canvasLostFocus, true);

document.onload = init();

function init() {
    OurGame.canvas = document.getElementById('canvas');
    OurGame.ctx = OurGame.canvas.getContext("2d");
    loadContext();
    initGameModes();

    setInterval(gameLoop, 1000 / OurGame.FPSlimit);
}
function initOnePlayerGame() {
    OurGame.gameModes = null;
    var p1 = new Player();
    p1.init(uniqueID());
    p1.assignKeys(KeyBoardType.ARROWS);
    OurGame.players.push(p1);

    var c1 = new SimpleAI();
    c1.init(uniqueID());
    OurGame.players.push(c1);
}

function initGameModes() {
    OurGame.canvas.addEventListener('mousedown', mouseDownOnButtons, false);
    OurGame.canvas.addEventListener('mousemove', mouseMoveOnButtons, false);
    var mode1 = {x:100, y:40, w:400, h:120, text:"Player vs Player", type:GameModeSelection.PLAYERvsPLAYER };
    var mode2 = {x:100, y:200, w:400, h:120, text:"Player vs AI", type:GameModeSelection.PLAYERvsAI };
    var mode3 = {x:100, y:360, w:400, h:120, text:"Multiplayer", type:GameModeSelection.MultiPLAYER };
    if (!OurGame.buttons) {
        OurGame.buttons = [];
    }
    OurGame.buttons.push(new GameMode(mode1));
    OurGame.buttons.push(new GameMode(mode2));
    OurGame.buttons.push(new GameMode(mode3));
}

function initTwoPlayerGame() {
    var p1 = new Player(uniqueID());
    p1.setPos(level.spawnPos.x[0], level.spawnPos.y[0]);
    p1.assignKeys(KeyBoardType.WASD);

    OurGame.players.push(p1);
    createPlayerSideBar(p1);

    var p2 = new Player(uniqueID());
    p1.setPos(level.spawnPos.x[1], level.spawnPos.y[1]);
    p2.assignKeys(KeyBoardType.ARROWS);
    OurGame.players.push(p2);
    createPlayerSideBar(p2);
    for (var i = 0; i < OurGame.players.length; i++) {
        level.map[Math.floor(OurGame.players[i].x / OurGame.grid)][Math.floor(OurGame.players[i].y / OurGame.grid)] = "p" + i;
    }
}

function loadContext() {
    loadImage("TilesSprite2");
    loadImage("spritesheet1");
    loadImage("backsheet1");
    loadImage("masks1");
}

level = {
    name:"Error 100 - Level not found",
    map:[],
    spawnPos:{
        "x":0,
        "y":0
    }
};

function canvasLostFocus(evt) {
    OurGame.keys = new Array();
}

function updateFPS() {
    OurGame.curFPS = OurGame.numFramesDrawn;
    OurGame.numFramesDrawn = 0;
}

function gameModeStarted() {
    if (!OurGame.isGameOver) {
        update();
        clear();
        draw();
    } else {
        draw();
        drawGameOver();
        drawButtons();
    }
}
function gameLoaded() {
    if (OurGame.gameModeSelected) {
        gameModeStarted();
    } else {
        draw();
        updateGameSelecionKeys();
    }
}
function gameLoop() {
    if (OurGame.contentLoaded && OurGame.mapLoaded) {
        gameLoaded();
    } else {
        drawLoading();
    }
}

function gameOverActivities() {
    OurGame.isGameOver = true;
    if (!OurGame.buttons) {
        OurGame.buttons = [];
    }
    OurGame.canvas.addEventListener('mousedown', mouseDownOnButtons, false);
    OurGame.canvas.addEventListener('mousemove', mouseMoveOnButtons, false);
    OurGame.buttons.push(new StartNewGame({x:220, y:400, w:180, h:50, text:"New Game"}));
}
function update() {
    for (var i = 0; i < OurGame.players.length; i++) {
        if (OurGame.players[i].isAlive()) {
            updateArrowKeys(OurGame.players[i]);
            if (OurGame.players[i].update(i.toString())) {
//                console.log("CHANGE!");
                var t2 = level.map[Math.floor(OurGame.players[i].x / OurGame.grid)][Math.floor(OurGame.players[i].y / OurGame.grid)].charAt(0);
                var t3 = level.map[Math.floor(OurGame.players[i].x / OurGame.grid)][Math.floor(OurGame.players[i].y / OurGame.grid)].charAt(1);
                if (t2 === "p" && t3 !== i.toString()) {
//                    console.log("lisan");
                    level.map[Math.floor(OurGame.players[i].x / OurGame.grid)][Math.floor(OurGame.players[i].y / OurGame.grid)] += ("p" + i);
//                    console.log( level.map[Math.floor(OurGame.players[i].x / OurGame.grid)][Math.floor(OurGame.players[i].y / OurGame.grid)]);
                } else {
                    level.map[Math.floor(OurGame.players[i].x / OurGame.grid)][Math.floor(OurGame.players[i].y / OurGame.grid)] = "p" + i;
                }

            }
        } else {
            gameOverActivities();
        }
    }
    for (i = 0; i < OurGame.bombs.length; i++) {
        if (OurGame.bombs[i] !== undefined) {
            OurGame.bombs[i].update();
            if (OurGame.bombs[i] !== undefined) {
                var t = level.map[Math.floor(OurGame.bombs[i].x / OurGame.grid)][Math.floor(OurGame.bombs[i].y / OurGame.grid)].charAt(0);
                if (t === "p") {
                    level.map[Math.floor(OurGame.bombs[i].x / OurGame.grid)][Math.floor(OurGame.bombs[i].y / OurGame.grid)] += ("b" + i);
                } else {
                    level.map[Math.floor(OurGame.bombs[i].x / OurGame.grid)][Math.floor(OurGame.bombs[i].y / OurGame.grid)] = "b" + i;
                }
            }
        }
    }
}

function drawButtons() {
    if (OurGame.buttons) {
        for (var k = 0; k < OurGame.buttons.length; k++) {
            OurGame.buttons[k].draw();
        }
    }
}
function draw() {
    drawBackground();
    drawWorld();
    drawBombExlposions();
    drawButtons();
//    drawClouds();
    drawMasks();
    drawHud();
}

function  drawBombExlposions(){
    for (var i = 0; i < OurGame.bombs.length; i++){
        if (OurGame.bombs[i])    {
            OurGame.bombs[i].drawExplosionExt();
        }
    }
}
function drawMasks() {
    OurGame.ctx.drawImage(OurGame.images["masks1"], 0, 25, 20, 280, 0, 0, 20, 512);  //left
    OurGame.ctx.drawImage(OurGame.images["masks1"], 65, 0, 280, 20, 0, 0, 608, 20); //top
    OurGame.ctx.drawImage(OurGame.images["masks1"], 20, 25, 20, 280, 588, 0, 20, 512); //right
    OurGame.ctx.drawImage(OurGame.images["masks1"], 65, 20, 280, 20, 0, 492, 608, 20); //right
}
function drawBackground() {
    var backgroundHorizontalSize = 5;
    var backgroundVerticalSize = 4;
    for (var i = 0; i < backgroundHorizontalSize; i++) {
        for (var j = 0; j < backgroundVerticalSize; j++) {
            if (i % 2 == 0) {
                OurGame.ctx.drawImage(OurGame.images["backsheet1"], 0, 0, OurGame.maxBackGrid, OurGame.maxBackGrid, (i * OurGame.backGrid) - OurGame.backOffset, (j * OurGame.backGrid) - OurGame.backOffset, OurGame.maxBackGrid, OurGame.maxBackGrid);
            } else {
                OurGame.ctx.drawImage(OurGame.images["backsheet1"], OurGame.maxBackGrid, 0, OurGame.maxBackGrid, OurGame.maxBackGrid, (i * OurGame.backGrid) - OurGame.backOffset, (j * OurGame.backGrid) - OurGame.backOffset, OurGame.maxBackGrid, OurGame.maxBackGrid);
            }
        }
    }
}

function drawWorld() {
    var mapHorizontalSize = level.map.length;
    var mapVerticalSize = level.map[0].length;

    for (var j = 0; j < mapVerticalSize; j++) {
        for (var i = 0; i < mapHorizontalSize; i++) {
            var t = level.map[i][j];
            var tnum = parseInt(t.substr(1, 2));
            switch (t.charAt(0)) {
                case 'w':
                    drawGridObject(OurGame.images["spritesheet1"], tnum, 1, (i * OurGame.grid) - OurGame.offSet, (j * OurGame.grid) - OurGame.offSet);
                    break;
                case 'h':
                    drawGridObject(OurGame.images["spritesheet1"], tnum + 4, 1, (i * OurGame.grid) - OurGame.offSet, (j * OurGame.grid) - OurGame.offSet);
                    break;
                case 'e':
                    drawGridObject(OurGame.images["spritesheet1"], tnum, 0, (i * OurGame.grid) - OurGame.offSet, (j * OurGame.grid) - OurGame.offSet);
                    break;
                case 'p':
                    var t2 = t.slice(2, 3);
                    switch (t2) {
                        case "b":
                            if (OurGame.bombs[parseInt(t.substr(3, 4))] !== undefined) {
                                OurGame.bombs[parseInt(t.substr(3, 4))].draw();
                            }
                            break;
                        case "p":
//                            console.log("teine!");
                            if (OurGame.players[parseInt(t.substr(3, 4))].isAlive()) {
                                OurGame.players[parseInt(t.substr(3, 4))].draw();
                            }
                            break;
                    }
                    if (OurGame.players[tnum].isAlive()) {
                        OurGame.players[tnum].draw();
                    }
                    break;
                case 'b':
                    if (OurGame.bombs[tnum] != undefined) {
                        OurGame.bombs[tnum].draw();
                    }
                    break;


            }
        }
    }
}

function drawClouds() {
    var dist = 700;
    for (var i = 0; i <= 2; i++) {
        OurGame.ctx.drawImage(OurGame.images["masks1"],
            45, 45, 55, 55,
            (OurGame.totalFramesDrawn + (dist / 2) * i) % (OurGame.canvas.width + dist + 55) - dist,
            (OurGame.totalFramesDrawn + (dist / 2) * i) % (OurGame.canvas.height + dist + 55) - dist,
            dist + 55, dist + 55);
        OurGame.ctx.drawImage(OurGame.images["masks1"],
            45, 45, 55, 55,
            (OurGame.totalFramesDrawn + (dist / 2) * i) % (OurGame.canvas.width + dist + 55) - dist,
            (OurGame.totalFramesDrawn + (dist / 2) * i + dist) % (OurGame.canvas.height + dist + 55) - dist,
            dist + 55, dist + 55);
    }

}

function drawHud() {
    OurGame.ctx.save();
    OurGame.ctx.setTransform(1, 0, 0, 1, 0, 0);

    //FPS
    OurGame.ctx.fillStyle = "#000";
    OurGame.ctx.font = "bold 12px sans-serif";
    OurGame.ctx.fillText("fps: " + OurGame.curFPS + "/" + OurGame.FPSlimit, 10, 20);
    ++OurGame.numFramesDrawn;
    ++OurGame.totalFramesDrawn;

    OurGame.ctx.restore();
}

function drawGameOver() {


    OurGame.ctx.save();

    OurGame.ctx.fillStyle = "#000";
    OurGame.ctx.globalAlpha = 0.6;
    OurGame.ctx.fillRect(0, 0, OurGame.canvas.width, OurGame.canvas.height);

    OurGame.ctx.fillStyle = "#FFF";
    OurGame.ctx.globalAlpha = 1;
    OurGame.ctx.font = 'bold 30px sans-serif';
    OurGame.ctx.lineWidth = 1;
    OurGame.ctx.fillText('Game Over!', OurGame.canvas.width / 2 - 80, OurGame.canvas.height / 2 - 20);
    OurGame.ctx.restore();
}
function drawLoading() {
    OurGame.ctx.save();
    OurGame.ctx.setTransform(1, 0, 0, 1, 0, 0);

    OurGame.ctx.clearRect(0, 0, OurGame.canvas.width, OurGame.canvas.height);

    OurGame.ctx.fillStyle = "#FFF";

    OurGame.ctx.font = 'bold 30px sans-serif';
    OurGame.ctx.lineWidth = 1;
    OurGame.ctx.strokeStyle = "#000";
    var dots = "";
    for (var i = 1; i < (OurGame.numFramesDrawn / 15 % 30); i++) {
        dots += ".";
        if (i > 2) {
            break;
        }
    }
    OurGame.numResourcesLoaded = 0;
    OurGame.totalResources = 1;
    OurGame.ctx.fillText('Loading' + dots, OurGame.canvas.width / 2 - 50, OurGame.canvas.height / 2 - 20);
    OurGame.ctx.strokeText('Loading' + dots, OurGame.canvas.width / 2 - 50, OurGame.canvas.height / 2 - 20);
    OurGame.ctx.fillText(OurGame.numResourcesLoaded + "/" + OurGame.totalResources, OurGame.canvas.width / 2 - 15, OurGame.canvas.height / 2 + 10);
    OurGame.ctx.strokeText(OurGame.numResourcesLoaded + "/" + OurGame.totalResources, OurGame.canvas.width / 2 - 15, OurGame.canvas.height / 2 + 10);
    ++OurGame.numFramesDrawn;

    OurGame.ctx.restore();
}

function clear() {
    // Store the current transformation matrix
    OurGame.ctx.save();
    // Use the identity matrix while clearing the canvas
    OurGame.ctx.setTransform(1, 0, 0, 1, 0, 0);
    OurGame.ctx.clearRect(0, 0, OurGame.canvas.width, OurGame.canvas.height);
    // Restore the transform
    OurGame.ctx.restore();
}